<template>
	<view v-if="user">
		<view v-if="user.power == 3">
			<fui-list v-for="(item,index) in list" :ket="index">
				<fui-list-cell arrow @click="toViews(item)" :highlight="true">
					<text>{{index + 1  +  item.classifyName}}</text>
				</fui-list-cell>
			</fui-list>
		</view>
		<view v-else>
			<fui-list v-for="(item,index) in list" :key="index">
				<fui-list-cell @longpress="onShow(item)" arrow @click="toViews(item)" :highlight="true">
					<text>{{index + 1  +  item.classifyName}}</text>
				</fui-list-cell>
			</fui-list>
		</view>
	</view>
	<view>
		<up-action-sheet :actions="columns" @select="onColumns" :round="10" @close="show=!show" :closeOnClickOverlay="true" title="更多" :show="show">
		</up-action-sheet>
	</view>
	<up-modal :show="showInfo" @confirm="saveInfo()" :title="title" @cancel="showInfo=false" :showCancelButton="true">
		<view class="slot-content">
			<view>
				<view class="c" style="width: 80rpx;">页码</view>
				<view style="width: 130rpx;">x</view>
				<view style="width: 130rpx;">y</view>
			</view>
			<view v-for="p in pageSize" class="row middle">
				<view class="c" style="width: 80rpx;">{{p}}</view>
				<fui-input number v-model="x[p-1]" placeholder="请输入" style="width: 130rpx;"></fui-input>
				<fui-input number v-model="y[p-1]" placeholder="请输入" style="width: 130rpx;"></fui-input>
			</view>
		</view>
	</up-modal>
</template>

<script>
	import hearder from '../../components/header/header.vue'
	import http from "@/common/api/index.js";
	import { BASE_IP } from '@/common/http/url.js'
	// #ifdef APP-PLUS
	const filePicker = uni.requireNativePlugin('Ba-FilePicker')
	const wpsTool = uni.requireNativePlugin("CL-WPSTool");
	const open = uni.requireNativePlugin("Html5App-openFile");
	const iOSFileSelect = uni.requireNativePlugin('YangChuan-YCiOSFileSelect');
	const lemonjkFileSelect = uni.requireNativePlugin('lemonjk-FileSelect');
	// #endif
	// #ifdef MP-WEIXIN
	const filePicker = ""
	const wpsTool = ""
	const open = ""
	const iOSFileSelect = ""
	const lemonjkFileSelect = ""
	// #endif

	export default {
		components: {
			hearder
		},
		data() {
			return {
				columns: [{ name: '上传文档', id: 1 }, { name: '设置盖章位置', id: 2 }, { name: '设置签名位置', id: 3 }, { name: '取消', id: 0 }],
				show: false,
				list: null,
				filePath: "",
				user: null,
				itme: "",
				type: 0,
				title: '',
				showInfo: false,
				pageSize: 0,
				x: [],
				y: [],
				isSubmit: false,
			};
		},
		onLoad() {
			let user = uni.getStorageSync('user');
			if (user == null || user == '' || user.unitId == '') {
				const pages = getCurrentPages();
				const currentPage = pages[pages.length - 1];
				const url = currentPage.route; // 页面路径（如 'pages/index/index'）
				const options = currentPage.options; // 页面参数对象
				uni.setStorageSync('url', '/' + url);
				uni.redirectTo({ url: '/pagesMine/wxLogin/wxLogin' });
				return;
			}
			this.user = user;
			this.getRecord();
		},
		methods: {
			onShow(res) {
				this.itme = res
				this.show = !this.show
			},
			onColumns(res) {
				console.log(res)
				console.log(this.itme)
				if (res.id == 1) {
					this.toUplod(this.itme)
				} else if (res.id == 2 || res.id == 3) {
					this.getInfo(res.id);
				}
			},
			getInfo(obj) {
				let _this = this;
				this.type = obj == 2 ? 0 : 1;
				this.title = "设置" + (this.type == 0 ? "盖章" : "签名") + "位置";
				let url = BASE_IP + "pc/classifyinfo/info/" + this.itme.classifyId + "/" + this.type;
				let user = uni.getStorageSync("user")
				uni.request({
					url: url,
					header: {
						"Authorization": user.token
					},
					success: (res) => {
						if (res.statusCode == 200) {
							_this.showInfo = true;
							console.log("ci", res.data);
							_this.pageSize = res.data[0];
							let info = res.data[1];
							_this.x = [];
							_this.y = [];
							_this.x = new Array(_this.pageSize);
							_this.y = new Array(_this.pageSize);
							for (let i = 0; i < _this.x.length; i++) {
								if (info.length > 0 && info[i][0]) {
									_this.x[i] = info[i][0];
								}
							}
							for (let i = 0; i < _this.y.length; i++) {
								if (info.length > 0 && info[i][1]) {
									_this.y[i] = info[i][1];
								}
							}
						}
					},
					fail: () => {
						uni.showToast({
							title: "服务器出现问题",
							icon: "error"
						})
						return
					}
				})
			},
			saveInfo() {
				if (this.isSubmit) {
					uni.showToast({
						title: "请勿重复提交",
						icon: "error"
					})
					return
				}
				let msg = '';
				for (let i = 0; i < this.x.length; i++) {
					if (this.x[i] === null || this.x[i] === undefined || this.x[i] === '') {
						msg = `x第${i+1}项未填写`;
						break;
					}
				}
				for (let i = 0; i < this.y.length; i++) {
					if (this.y[i] === null || this.y[i] === undefined || this.y[i] === '') {
						msg = `y第${i+1}项未填写`;
						break;
					}
				}
				if (msg != '') {
					uni.showToast({
						title: msg,
						icon: 'error'
					})
					return false;
				}
				let _this = this;
				let url = BASE_IP + "pc/classifyinfo/save";
				let user = uni.getStorageSync("user")
				let info = {
					pageSize: this.pageSize,
					x: this.x,
					y: this.y
				};
				this.isSubmit = true;
				uni.request({
					url: url,
					header: {
						"Authorization": user.token,
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					data: {
						classifyId: _this.itme.classifyId,
						type: _this.type,
						json: JSON.stringify(info),
						uuid: user.uuid
					},
					method: "POST",
					success: (res) => {
						if (res.statusCode == 200) {
							console.log("cs", res.data);
							_this.isSubmit = false;
							_this.showInfo = false;
							uni.showToast({
								title: "保存成功",
								icon: "success"
							})
						}
					},
					fail: () => {
						_this.isSubmit = false;
						uni.showToast({
							title: "服务器出现问题",
							icon: "error"
						})
						return
					}
				})
			},
			toDetails(data) {
				if (data.classifyId == 19) {
					uni.navigateTo({
						url: "/pagesWork/callthepolice/callthepolice"
					})
					return
				}
				console.log(data)
			},
			getRecord() {
				uni.showLoading();
				let user = uni.getStorageSync("user")
				this.user = user
				let url = BASE_IP + "pc/classify/query"
				uni.request({
					url: url,
					header: {
						"Authorization": user.token
					},
					success: (res) => {
						uni.hideLoading();
						console.log("工作记录", res);
						if (res.statusCode == 200) {
							this.list = res.data
						}
					},
					fail: () => {
						uni.showToast({
							title: "服务器出现问题",
							icon: "error"
						})
						return
					}
				})
			},
			toUplod(itme) {
				// uni.openAppAuthorizeSetting({
				//   success (res) {
				//     console.log(res)
				//   }
				// })

				uni.showModal({
					title: "提示",
					content: "请选择.docx文档(此文档需要特殊处理，上传前请联系管理员)",
					showCancel: false,
					success: (res) => {
						if (res.confirm) {
							if (uni.getSystemInfoSync().platform == 'ios') {
								console.log("ios")
								lemonjkFileSelect.showPicker({
									mimeType: "*/*",
									utisType: ["public.data"],
									pathScope: "/Download",
									navTitle: "文件选择",
									theme: 'auto', //auto 跟随系统  light 亮色  dark 暗色 
									showHideFile: "yes", //是否显示隐藏的文件和文件夹      
									filterConfig: { //对象里配置的属性要同时满足   
										// fileName:['base.apk','config.txt','配置文件.yaml'],  //属性数组满足其中一项
										fileSize: String(1 * 1024 * 1024), // 单位：byte(字节)  //属性数组满足其中一项
										fileExtension: ['docx'], //属性数组满足其中一项 
									}
								}, result => {
									console.log(result);
									console.log(result.files[0].filePath);
									if (result.files[0].fileExtension == "docx") {
										let path = result.files[0].filePath

										let url = BASE_IP + "pc/classify/upload/" + itme.classifyId
										this.upload(url, path)
									} else {
										uni.showModal({
											title: "提示",
											content: "请选择docx文档",
											showCancel: false
										})
									}
								})
							} else {
								console.log("安卓")
								lemonjkFileSelect.isHaveSecurityScopeGrant({
									type: "FILE_PERMISSION" //不填默认为"FILE_PERMISSION"，可选值："FILE_PERMISSION"（用于自定义文件选择器相关权限查询）
								}, result => {

									if (result.result == "yes") {
										//有权限,可以直接唤起自定义文件选择器
										// lemonjkFileSelect.showPicker()
										lemonjkFileSelect.showPicker({
											mimeType: "*/*",
											utisType: ["public.data"],
											pathScope: "/Download",
											navTitle: "文件选择",
											theme: 'auto', //auto 跟随系统  light 亮色  dark 暗色 
											showHideFile: "yes", //是否显示隐藏的文件和文件夹      
											filterConfig: { //对象里配置的属性要同时满足   
												// fileName:['base.apk','config.txt','配置文件.yaml'],  //属性数组满足其中一项
												fileSize: String(1 * 1024 *
													1024), // 单位：byte(字节)  //属性数组满足其中一项
												fileExtension: ['docx'], //属性数组满足其中一项 
											}
										}, result => {
											console.log(result);
											console.log(result.files[0].filePath);
											if (result.files[0].fileExtension == "docx") {
												let path = result.files[0].filePath
												let url = BASE_IP + "pc/classify/upload/" +
													itme.classifyId
												this.upload(url, path)
											} else {
												uni.showModal({
													title: "提示",
													content: "请选择docx文档",
													showCancel: false
												})
											}

										})
									} else {
										//无权限,询问用户是否同意申请权限
										uni.showModal({
											content: "需要申请文件访问权限，是否同意",
											success(e) {
												if (e.confirm) {
													lemonjkFileSelect
														.reqCustomPickerPermission({},
															result => {

																console.log(result);
															})
												} else {

												}
											}
										})
									}
								})
							}
						}
					}
				})


				// lemonjkFileSelect.reqCustomPickerPermission({}, result => {
				// 	if (result.code == 3002) {
				// 		//用户同意了权限,可以唤起自定义文件选择器
				// 		//lemonjkFileSelect.showPicker()
				// 	} else {
				// 		//用户拒绝了权限
				// 		uni.showToast({
				// 			title: "你拒绝了授权"
				// 		})
				// 	}
				// 	console.log(result);
				// })
				// this.requestMultiplePermissions()
				//4.0.0+ 安卓自定义文件选择器使用及高级筛选器配置示例
				// lemonjkFileSelect.showPicker({
				// 	mimeType: "*/*",
				// 	utisType: ["public.data"],
				// 	pathScope: "/Download",
				// 	navTitle: "文件选择",
				// 	navTextColor: '#55ff00',
				// 	navBarBgColor: '#00aaff',
				// 	theme: 'auto', //auto 跟随系统  light 亮色  dark 暗色 
				// 	showHideFile: "yes", //是否显示隐藏的文件和文件夹      
				// 	filterConfig: { //对象里配置的属性要同时满足   
				// 		// fileName:['base.apk','config.txt','配置文件.yaml'],  //属性数组满足其中一项
				// 		fileSize: String(1 * 1024 * 1024), // 单位：byte(字节)  //属性数组满足其中一项
				// 		fileExtension: ['docx', 'txt', 'jpg', 'mp3', 'yaml'], //属性数组满足其中一项 
				// 	}
				// }, result => {
				// 	console.log(result);
				// })

				// if (uni.getSystemInfoSync().platform == 'ios') {

				// 	// apple document-types 文件类型参数 https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
				// 	// 文件类型参数
				// 	let params = {
				// 		"document-types": [".docx", ],
				// 		"isBase64": 0
				// 	}
				// 	let _this = this
				// 	uni.showModal({
				// 		title: "提示",
				// 		content: "请选择.docx文档(此文档需要特殊处理，上传前请联系管理员)",
				// 		showCancel: false,
				// 		success: () => {
				// 			iOSFileSelect.show(params, result => {
				// 				let status = parseInt(result.status);
				// 				// 状态200选取成功
				// 				if (status == 200) {
				// 					let url = result.url;
				// 					uni.downloadFile({
				// 						url: url,
				// 						success: function(res) {
				// 							if (res.statusCode == 200) {
				// 								// filePath 可用于 uni.uploadFile 上传的路径
				// 								let filePath = res.tempFilePath;
				// 								_this.uploads(item, filePath)
				// 								console.log(filePath)
				// 							}
				// 						}
				// 					});
				// 				}
				// 			});
				// 		}
				// 	})

				// 	return
				// }

				// let user = uni.getStorageSync("user")
				// let url = BASE_IP + "pc/classify/upload/" + itme.classifyId
				// this.upload(url, res.data[0].absolutePath)
				// this.selctFile(url)
			},
			requestMultiplePermissions() {
				const permissions = ['scope.writePhotosAlbum', 'scope.camera'];
				permissions.forEach(permission => {
					uni.authorize({
						scope: permission,
						success() {
							console.log(`用户已授权 ${permission}`);
						},
						fail(err) {
							console.error(`用户拒绝授权 ${permission}`, err);
							if (err.errMsg === 'authorize:fail auth deny') {
								uni.showModal({
									title: '提示',
									content: `需要开启${permission}权限才能正常使用该功能，请前往设置页面开启权限。`,
									success(res) {
										if (res.confirm) {
											console.log('用户点击确定');
											uni.openSetting({
												success(settingData) {
													console.log('openSetting success',
														settingData.authSetting);
												}
											});
										} else if (res.cancel) {
											console.log('用户点击取消');
										}
									}
								});
							}
						}
					});
				});
			},
			toDoc(itme, read) {
				let url = BASE_IP + itme.upload
				if (itme.upload === null) {
					uni.showModal({
						title: "提示",
						content: "此文件未上传，请联系管理员",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								return
							}
						}
					})
				}
				if (this.user.power == 2) {

					if (uni.getSystemInfoSync().platform === 'android') {
						let is = open.isLoadTbs();
						if (!is) {
							this.installLocalTbs()
							return
						}
						uni.downloadFile({
							url: url,
							success: (res) => {
								uni.hideLoading()
								if (res.statusCode === 200) {
									const {
										tempFilePath
									} = res;
									let filePath = plus.io.convertLocalFileSystemURL(tempFilePath);
									open.openFile({
										filename: filePath,
										isShowBackIcon: true
									}, ret => {});
								}
							},
							fail: (e) => {
								uni.hideLoading()
								console.log(e);
								uni.showModal({
									content: JSON.stringify(e) + "失败"
								})
							}
						})
					} else {
						uni.downloadFile({
							url: url,
							success: (res) => {
								uni.hideLoading()
								if (res.statusCode === 200) {
									const {
										tempFilePath
									} = res;
									let filePath = plus.io.convertLocalFileSystemURL(tempFilePath);
									open.openFile({
										filename: filePath,
										isShowBackIcon: true
									}, ret => {});
								}
							},
							fail: (e) => {
								uni.hideLoading()
								console.log(e);
								uni.showModal({
									content: JSON.stringify(e) + "失败"
								})
							}
						})
					}

					return
				}

				if (read == null || read == "" || read == undefined || read == false) {
					this.editorUrlnDoc(url, itme, true)
				}
				this.editorUrlnDoc(url, itme, false)
			},
			installLocalTbs() {
				let url = BASE_IP + "static/tbs/arm64-v8a.tbs"
				uni.downloadFile({
					url: url,
					success: (res) => {
						if (res.statusCode == 200) {
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: (r) => {
									let filepath = plus.io.convertLocalFileSystemURL(r
										.savedFilePath);
									open.installLocalTbs({
										tbsFilePath: filepath,
										isdelete: false //安装好是否要删除该文件
									}, function(e) {
										console.log("安装 tbs 内核" + JSON.stringify(e));
										if (e.code == 0) {
											uni.showToast({
												title: "安装TBS 请重新打开",
												icon: "none"
											});
										} else {
											uni.showToast({
												title: e.msg,
												icon: "none"
											});
										}
									});
								}
							})
						}
					}
				})
				//安装 tbs 离线内核, 在适当的时候安装tbs 浏览内核,安装一次即可
			},
			selctFile(url) {
				uni.showModal({
					title: "提示",
					content: "请选择.docx文档(此文档需要特殊处理，上传前请联系管理员1)",
					confirmText: "我已知晓",
					success: (res) => {
						if (res.confirm) {
							filePicker.selectFile({ //自定义类型分组
									selectType: 0,
									maxCount: 1,
									groupTypes: [{
										name: "文档",
										fileTypes: ["docx", "xls", "xlsx"]
									}],
									filetypes: "docx"
								},
								(res) => {
									if (res.data) {
										const maxSizeInBytes = 10 * 1024 * 1024
										this.filePath = res.data[0].absolutePath
										if (res.data.length > 1) {
											uni.showModal({
												title: "提示",
												content: "仅支持单个文件上传",
												showCancel: false,
												success: (res) => {
													if (res.confirm) {
														return
													}
												}
											})
											return
										}
										if (res.data[0].size > maxSizeInBytes) {
											uni.showToast({
												title: "文件过长",
												icon: "error"
											})
											return
										}
										this.upload(url, res.data[0].absolutePath)
									}
								});
						}
					}
				})
			},
			/**
			 * @param {Object} url 上传文件的服务器地址
			 * @param {Object} filePath 本地文件的路径
			 */
			upload(url, filePath) {
				console.log("调用上传路径：", url, "文件路径：", filePath)
				let user = uni.getStorageSync("user")
				uni.uploadFile({
					header: {
						"Authorization": user.token,
					},
					name: "file",
					url: url,
					filePath: filePath,
					success: (res) => {
						if (res.statusCode == 200) {
							uni.showToast({
								title: "上传成功",
								icon: "success"
							})
							this.getRecord()
						}
					},
					fail: (res) => {
						uni.showToast({
							title: "上传失败,请重试",
							icon: "error"
						})
					}
				})
			},
			editorUrlnDoc(url, itme, read) {
				uni.downloadFile({
					url: url,
					success: (res) => {
						uni.hideLoading()
						if (res.statusCode === 200) {
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: (data) => {
									// console.log("原始文件保存路径：",data)
									let tempFilePath = data.savedFilePath
									let filePath = plus.io.convertLocalFileSystemURL(tempFilePath);
									// console.log("转换的文件路径：",filePath)
									this.openDocInfo(filePath, true, itme);
								}
							})

						}
					},
					fail: (e) => {
						uni.hideLoading()
						console.log(e);
						uni.showModal({
							content: JSON.stringify(e) + "失败"
						})
					}

				})

			},
			openDocInfo(filePath, isEditor, itme) {
				if (!isEditor) {
					wpsTool.wpsOpenFile(filePath, result => {

					})
				} else {
					let user = uni.getStorageSync("user")
					let options = {
						filePath: filePath, //文件路径 必填
						userName: user.userName, //必填，用于记录编辑信息
						isEnterReviseMode: true //是否进入修订模式,默认true
					};
					let url = BASE_IP + "pc/classify/upload/" + itme.classifyId
					wpsTool.wpsEditorFile(options, result => {

						const {
							code,
							msg
						} = result;
						if (code == 1) {
							//成功;
							let newPath = result.path; //该路径为绝对路径;
							let relativepath = plus.io.convertAbsoluteFileSystem(newPath); //为平台的相对路径，可以用于上传到服务器;
							this.path = newPath;
							this.upload(url, relativepath)
						} else {
							uni.showModal({
								title: "提示",
								content: "抱歉，文档查看失败",
								success: (res) => {
									return
								},
								showCancel: false
							})
						}
					})
				}
			},
			toViews(itme) {
				if (itme.upload == null) {
					uni.showModal({
						title: "提示",
						content: "文档未上传，请联系管理员上传文档",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								return
							}
							if (res.cancel) {
								return
							}
						}
					})
					return
				}
				let classifyId = itme.num
				let id = parseInt(classifyId)
				let data = JSON.stringify(itme)
				console.log(data)
				let url = "/pagesWork/record/record_details?data=" + data
				uni.navigateTo({ url: url })
			}
		},
	}
</script>

<style lang="scss">
	body {
		background-color: rgb(247, 247, 247);
	}

	.list {
		background-color: white;
		height: 80rpx;
		width: 90%;
		border-radius: 15rpx;
		border-bottom: 2px solid #eeeeee;
		margin: auto;
		margin-top: 10px;
		color: #606266;
		font-weight: bold;
		padding-left: 20rpx;
		font-size: 10px;
		margin-bottom: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.list-btn {
		width: 80%;
		height: 100%;
		display: flex;
		flex-direction: row-reverse;
		justify-content: space-between;
		align-items: center;
		margin: auto;
		padding-bottom: 20rpx;
	}

	.slot-content {
		width: 100%;
		border: 1px solid #e0e0e0;
		border-radius: 4px;
		overflow: hidden;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
	}

	.slot-content>view {
		display: flex;
	}

	.slot-content>view:first-child {
		background-color: #f5f5f5;
		font-weight: bold;
	}

	.slot-content>view:first-child>view {
		padding: 12px 15px;
		border-right: 1px solid #e0e0e0;
	}

	.slot-content>view {
		border-top: 1px solid #e0e0e0;
	}

	.slot-content>view>view,
	.slot-content>view>fui-input {
		flex: 1;
		padding: 10px 15px;
		border-right: 1px solid #e0e0e0;
	}

	.slot-content>view>fui-input {
		background-color: #fff;
	}

	.slot-content>view>view:last-child,
	.slot-content>view>fui-input:last-child {
		border-right: none;
	}

	.c {
		text-align: center;
	}
</style>